<?php

namespace common\logics\order\handle;

use Yii;
use yii\db\Exception;
use common\models\shop\ShopOrder;
use common\models\trade\Trade;
use common\logics\order\OrderUnifiedLogic;
use common\logics\order\RecordOrderLog;

/**
 * 订单删除模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class OrderDeleteHandle extends OrderBaseHandle {

    /**
     * @var string 统一订单模型基类
     */
    public $modelClass = OrderUnifiedLogic::class;

    /**
     * @var string 订单操作类型
     */
    public $handle = parent::HANDLE_DELETE;

    /**
     * 订单附加扩展校验
     * @param string $attribute
     * @param OrderUnifiedLogic $model
     */
    public function afterValidateOrder($attribute, $model) {
        $hasTrade = Trade::findByBizno($model->order_no)->andWhere([
            '>=', 'status', Trade::STATUS_DEFAULT
        ])->exists();
        if ($hasTrade) {
            $this->addError($attribute, '当前订单存在未处理的交易信息，不能删除！');
        }
    }

    /**
     * 删除订单
     * @return OrderUnifiedLogic
     * @throws Exception
     */
    protected function transactDelete() {
        $model = $this->getModel();
        $model->status = OrderUnifiedLogic::STATUS_CLOSE;
        $model->deleted_at = time();
        if (!$model->save()) {
            throw new Exception('订单删除失败，' . $model->getErrorMsg());
        }
        $orders = $model->orders;
        foreach ($orders as $order) {
            $order->status = ShopOrder::STATUS_CLOSE;
            $order->deleted_at = time();
            if (!$order->save()) {
                throw new Exception('订单删除失败，' . $order->getErrorMsg());
            }

            //记录订单日志
            RecordOrderLog::safeRecord($order, null, $this->operator);
        }
        return $model;
    }

}
